module.exports = {
  success(data, message = '成功', code = 0) {
    this.body = {
      code,
      success: code === 0,
      message,
      data
    };
  },
  successPage(data, message = '成功', code = 0) {
    const { data: oData, ...rest } = data || {};
    this.body = {
      code,
      success: code === 0,
      message,
      data: {
        ...rest,
        content: oData
      }
    };
  },
  error(message, data = undefined, code = -1) {
    this.body = {
      code,
      message,
      data,
      success: code === 0
    };
  },
  paging() {
    const { page = 1, size = 20 } = this.request.query || this.request.body;
    return {
      limit: size,
      offset: (page - 1) * size,
      page: page
    };
  },
  appendQuery(where, ...names) {
    names.forEach((name) => {
      const value = this.request.query[name];
      if (value !== undefined) where[name] = value;
    });
  },
  appendQueryLike(where, ...names) {
    const Literal = this.app.mysql.literals.Literal;
    names.forEach((name) => {
      const value = this.request.query[name];
      if (value !== undefined) where[name] = new Literal(`like '%${value}%'`);
    });
  },
  assetEmpty(value, name) {
    const err = new Error(`${name}不能为空`);
    if (value === '' || value === undefined) throw err;
  },
  NonEmptyQuery(key, name) {
    const value = this.request.query[key];
    this.assetEmpty(value, name);
    return value;
  },
  NonEmptyBody(key, name) {
    const value = this.request.body[key];
    this.assetEmpty(value, name);
    return value;
  },
  jiami(value) {
    const RdChats = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const RdChatsLength = RdChats.length;
    const randomNumber = (Math.floor(Math.random() * 9) + 1);
    const getRandChar = (num = 1) => {
      let result = '';
      for (let i = 0; i < num; i++) {
        result = `${result}${RdChats.charAt(Math.floor(Math.random() * RdChatsLength))}`;
      }
      return result;
    };
    const insertRandomCode = value.split('')
      .map(t => `${t}${getRandChar()}`)
      .join('');

    let result = `${insertRandomCode.length}${getRandChar(randomNumber)}${insertRandomCode}`;

    result = `${result}${getRandChar(31 - result.length)}${randomNumber}`;

    return result;
  }
};
